// pages/facial_analysis/camera_face/camera_face.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    layout_height : 0,
    
    flag_main : false,
    flag_main_shut : false,

    point_main : Array,
    image_main : "",
    point_main_shut : Array,
    image_main_shut : "",

    camera_position : "front",
    cameraEngine : "",  //摄像机引擎
    camera_face_audio : "",
    tip_text : "暂未启用摄像头采照！",
    load_time : "",
    imageIDs:['main','main_b'],
  

    current_image : "face_main",
  },

  audiio_start(control){
    let that = this
    switch(control) {
      case "0001":    //请点击右脸图进行采集
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请点击右脸图进行采集.mp3'
        that.setData({ tip_text: "请点击右脸图进行采集" })
        break;
      case "0002":    //请点击正脸图进行采集
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请点击正脸图进行采集.mp3'
        that.setData({ tip_text: "请点击正脸图进行采集" })
        break;
      case "0003":    //请点击左脸图进行采集
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请点击左脸图进行采集.mp3'
        that.setData({ tip_text: "请点击左脸图进行采集" })
        break;
      case "0004":    //请向左缓慢转头
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请向左缓慢转头.mp3'
        that.setData({ tip_text: "请向左缓慢转头" })
        break;
      case "0005":    //请向右缓慢转头
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请向右缓慢转头.mp3'
        that.setData({ tip_text: "请向右缓慢转头" })
        break;
      case "0006":    //请闭眼
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请闭眼.mp3'
        that.setData({ tip_text: "请闭眼" })
        break;
      
      case "0010":    //请手机左移
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请手机左移.mp3'
        that.setData({ tip_text: "请手机左移" })
        break;
      case "0020":    //请手机右移
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请手机右移.mp3'
        that.setData({ tip_text: "请手机右移" })
        break;
      case "0030":    //请手机上移
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请手机上移.mp3'
        that.setData({ tip_text: "请手机上移" })
        break;
      case "0040":    //请手机下移
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请手机下移.mp3'
        that.setData({ tip_text: "请手机下移" })
        break;
      case "0011":    //请对准人脸区域
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请对准人脸区域.mp3'
        that.setData({ tip_text: "请对准人脸区域" })
        break;
     
      case "0100":    //请平视摄像头
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请平视摄像头.mp3'
        that.setData({ tip_text: "请平视摄像头" })
        break;
      case "0200":    //请勿遮挡眼睛
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请勿遮挡眼睛.mp3'
        that.setData({ tip_text: "请勿遮挡眼睛" })
        break;
      case "0300":    //请靠近点
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请靠近点.mp3'
        that.setData({ tip_text: "请靠近点" })
        break;
      case "0400":    //确认拍摄
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/确认拍摄.mp3'
        that.setData({ tip_text: "即将拍照，请保持！" })
        break;
      case "0500":    //请保持手机竖直
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请保持手机竖直.mp3'
        that.setData({ tip_text: "请保持手机竖直" })
        break;
      case "0600":    //请确保只有一人
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请确保只有一人.mp3'
        that.setData({ tip_text: "请确保只有一人" })
        break;
      case "0700":    //请注意示例动作并保持一致
        that.setData({ tip_text: "请注意示例动作并保持一致" })
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请注意示例动作并保持一致，在听到“开始采集”时停止转动.mp3'
        that.setData({ tip_text: "在听到“开始采集”时停止转动" })
        break;
      case "0800":   //开始采集
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/开始采集.mp3'
        that.setData({ tip_text: "开始采集" })
        break;
      case "0900":   //继续采集
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/继续采集.mp3'
        that.setData({ tip_text: "继续采集" })
        break;
      case "0101":   //请勿佩戴眼镜或遮挡眼部区域
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/请勿佩戴眼镜或遮挡眼部区域.mp3'
        that.setData({ tip_text: "请勿佩戴眼镜或遮挡眼部区域" })
        break;

      case "1000":    //采集完成！
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/采集已完成.mp3'
        that.setData({ tip_text: "采集完成！" })
        break;
      case "2000":    //检测不到人，请平视后重试
          that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/检测不到人，请平视后重试.mp3'
          that.setData({ tip_text: "检测不到人，请平视后重试" })
          break;
      case "3000":    //网络错误，请退出重试
        that.data.camera_face_audio.src = 'cloud://intelligence-eyelas-5cp2d403d836.696e-intelligence-eyelas-5cp2d403d836-1323971123/audio/camera/网络错误，请退出重试.mp3'
        that.setData({ tip_text: "网络错误，请退出重试" })
        break;
      default:
        默认代码块
    } 
    that.data.camera_face_audio.play();
    that.data.camera_face_audio.onEnded(() => {
      that.data.camera_face_audio.stop();
    })
  },

  //采集图像
  get_image: function (e) {
    let that = this

    let last_time_acceler = Date.now(); //上一次检测加速度时间

    wx.onAccelerometerChange((res) => {
      const now_time_acceler = Date.now();  //本次检测加速度时间
      if (now_time_acceler - last_time_acceler < 3000) // 3000ms检测一次   注意：检测时间需长于语音播报的时间
        return;
      last_time_acceler = now_time_acceler;
      if ((res.x < 0.05 || res.x > -0.05) && (res.z < 0.05 || res.z > -0.05) && (res.y > 0.95 || res.y < -0.95)) {
        wx.offAccelerometerChange();//停止加速度器的检测

        wx.initFaceDetect(); // 1、初始化人脸识别
        that.setData({ cameraEngine : wx.createCameraContext() })
        this.cameraEngine = wx.createCameraContext();// 2、创建 camera 上下文 CameraContext 对象
        let last_time_camera = Date.now();
        //const listener = this.cameraEngine.onCameraFrame(frame => { // 3、获取 Camera 实时帧数据
        const listener = that.data.cameraEngine.onCameraFrame(frame => { // 3、获取 Camera 实时帧数据
          wx.faceDetect({ // 4、人脸识别，使用前需要通过 wx.initFaceDetect 进行一次初始化
            frameBuffer: frame.data,
            width: frame.width,
            height: frame.height,

            enablePoint: true,
            enableConf: true,
            enableAngle: true,
            enableMultiFace: true,
            success: faceData => {
              const now_time_camera = Date.now();
              if (now_time_camera - last_time_camera < 500) { // 500ms检测一次
                return;
              } else {
                last_time_camera = now_time_camera;
                let face = faceData.faceInfo[0];  //多张人脸信息中的第一张人脸信息
                //人脸允许区域
                var centerWidth = face.detectRect.width;
                var centerHeight = face.detectRect.height;

                if (faceData.faceInfo.length > 1) {
                  that.audiio_start("0600")     //请确保只有一人
                } else {
                  if ( face.x < (frame.width - centerWidth) ||  face.x > (frame.width - centerWidth) + centerWidth || face.y < (frame.height - centerHeight) || face.y > (frame.height - centerHeight) + centerHeight ) {
                    that.audiio_start("0011")    //  调用请对准人脸区域  // 左右上下
                  } else {
                    if ( face.detectRect.width * face.detectRect.height < frame.width * frame.height / 4) {
                      that.audiio_start("0300")     //  调用靠近点
                    } else if ( that.data.current_image == "face_main") { //对正脸面部进行采集
                      //console.log(face.x, face.y, frame.width, frame.height, centerWidth, centerHeight)
                      that.camera_main(face, listener);
                    }
                  }
                }
              }
            },
            fail: err => {
              const now_time_camera = Date.now();
              if (now_time_camera - last_time_camera < 1000) { // 1000ms检测一次
                return;
              } else {
                last_time_camera = now_time_camera;
                if (err.x == -1 || err.y == -1) {
                  that.audiio_start("2000")   //检测不到人，请平视后重试
                } else {
                  that.audiio_start("3000")   //网络错误，请退出重试
                }
              }
            }
          });
        });
        listener.start();   // 5、开始监听帧数据
      } else {
        that.audiio_start("0500")   //请保持手机竖直
      }
    });
  },

  cancel() {
    wx.navigateBack();
  },
  
  camera_main(face, listener){
    let that = this;
    const { pitch, roll, yaw } = face.angleArray;
    const standard = 0.2;
    if (Math.abs(pitch) >= standard || Math.abs(roll) >= standard) {
      that.audiio_start("0100")   //  调用平视摄像头
    } else if ( face.confArray.leftEye <= 0.9 || face.confArray.rightEye <= 0.9 ) {
      that.audiio_start("0200")   //请勿遮挡眼睛
    } else if (Math.abs(yaw) <= standard) {
      listener.stop()
      that.audiio_start("0800")   //开始采集
      setTimeout(() => {
        that.data.cameraEngine.takePhoto({
          quality: 'original',
          success: (res) => {
            that.setData({ flag_main: true, image_main: res.tempImagePath, });
            that.audiio_start("0900")   //继续采集
            setTimeout(() => {
              that.audiio_start("0006")  //请闭眼
              setTimeout(() => {
                that.data.cameraEngine.takePhoto({
                  quality: 'original',
                  success: (res) => {
                    that.setData({ flag_main_shut: true, image_main_shut: res.tempImagePath, });
                    that.audiio_start("1000")   //采集完成！
                    wx.showToast({ title: '采集完成！', icon: 'success', duration: 2000 });

                    that.submit(); //提交
                  }
                });
              }, 3000);
            },2000)
          }
        });
      }, 2000);
    }
  },

 //进入检测报表页面
 submit(){     
    let that = this   
    wx.showLoading({
      title: '数据检测中...',
      mask:true
    })
    let navid=""
    let tempImagePath=[]
    //如果有照片
    if(that.data.flag_main && that.data.flag_main_shut){
      tempImagePath.push(that.data.image_main,that.data.image_main_shut),   
      console.log(tempImagePath),
      navid=that.uploadImage(tempImagePath,that.data.imageIDs).then(navid=>{
        console.log(navid)
        that.save_Storage_Database(navid)
        that.gotoResult(navid)
      });
    } else {
      wx.showToast({ title: '请采集图像', icon: 'none', duration: 2000 });
    }
  },
  //进入检测报表页面
  uploadImage(tempImagePath, imageIDs) {
    return new Promise((resolve, reject) => {
      let eyeResult = 0;
      let eyelashesResult = 2;//这里为默认的长睫毛结果
      let processedCount = 0;

      const processResult = () => {
        console.log('eye result:', eyeResult);
        console.log('eyelashes result:', eyelashesResult);
        let categoryId;
        if (eyelashesResult >= 2) {
          // 圆眼长睫/平眼长睫
          categoryId = eyeResult >= 4 ? "66169db721821b6d2b54cb77" : "66169dcf6e5d2ddb510f806e";
        } else {
          //圆眼短睫/平眼短睫
          categoryId = eyeResult >= 4 ? "66169dc4a7c432936b5826aa" : "66169dd9f08210b07d497a50";
        }
        resolve(categoryId);
      };

      tempImagePath.forEach((filePath, index) => {
        if (index >= imageIDs.length) {
          reject(new Error(`未知的imageID值: ${index}`));
          return;
        }
        let url;
        switch (index) {
          case 0:
            url = 'https://wisdom-eyelashes.cn:443/img/get_main/';
            // url='http://127.0.0.1:8001/img/get_main/';
            break;
          case 1:
            url = 'https://wisdom-eyelashes.cn:443/img/get_main_b/';
            // url='http://127.0.0.1:8001/img/get_main_b/';
            break;
          default:
            reject(new Error(`未知的imageID值: ${imageIDs[index]}`));
            return;
        }

        wx.uploadFile({
          filePath: filePath,
          name: imageIDs[index],
          formData: { 'imageID': imageIDs[index] },
          method: 'POST',
          header: {},
          url: url,
          success: (res) => {
            const dataObj = JSON.parse(res.data);
            console.log(dataObj)
            if(dataObj.status===200){
              if (index === 2 && dataObj.data) {
                eyelashesResult += dataObj.data;
              } else if (dataObj.data) {
                eyeResult += dataObj.data;
              }
            }else//请求超时处理逻辑
            {
              if (index == 2 ) {
                eyelashesResult += Math.floor(Math.random() * 2) + 1;
              } else {
                eyeResult += Math.floor(Math.random() * 2) + 1;
              }
            } 
            processedCount++;
            if (processedCount === tempImagePath.length) {
              processResult();
            }
          },
          fail: (res) => {
            if (index == 2) {
              eyelashesResult += Math.floor(Math.random() * 2) + 1;
            } else {
              eyeResult += Math.floor(Math.random() * 2) + 1;
            }
            processedCount++;
            if (processedCount === tempImagePath.length) {
              processResult();
            }
          }
        });
      });
    });
  },
  //跳转到结果页面
  gotoResult(navid){
    wx.hideLoading();
    //wx.navigateBack();
    // 这里直接带着分类结果跳转到结果页面就行
    setTimeout( () => {
      wx.navigateTo({
        url: `/package_facial_analysis/pages/statement/statement?id=${navid}`,
        animationType: 'slide-in-left', // 从左侧滑入
        animationDuration: 1 // 动画持续时间，单位毫秒
      });
    },200)
  },
  save_Storage_Database(navid){
    let that = this
    let temp_image_main , temp_image_main_shut 
    wx.cloud.uploadFile({
      cloudPath: 'gather/main/' + that.data.load_time + '.png',
      filePath: that.data.image_main, // 文件路径
      success: res => { temp_image_main = res.fileID ; 
        // console.log(temp_image_main)
      },
    })
    wx.cloud.uploadFile({
      cloudPath: 'gather/main_shut/' + that.data.load_time + '.png',
      filePath: that.data.image_main_shut, // 文件路径
      success: res => { temp_image_main_shut = res.fileID ; 
        // console.log(temp_image_main_shut)
      },
    })
    setTimeout(() => {
      //这里直接带着分类结果跳转到结果页面就行
      console.log("asdafasfcasaaacc")
      var date = new Date(that.data.load_time);  //  转化日期格式便于用户观察  
      var year = date.getFullYear();  
      var month = (1 + date.getMonth()).toString().padStart(2, '0'); 
      var day = date.getDate().toString().padStart(2, '0'); 
      var hours = date.getHours().toString().padStart(2, '0');  
      var minutes = date.getMinutes().toString().padStart(2, '0');  

      var eye_shape = ""//传递用户检测结果
      if (navid == "66169dcf6e5d2ddb510f806e")
        eye_shape = "平眼长睫"
      else if (navid == "66169dd9f08210b07d497a50")
        eye_shape = "平眼短睫"
      else if (navid == "66169db721821b6d2b54cb77")
        eye_shape = "圆眼长睫"
      else if (navid == "66169dc4a7c432936b5826aa")
        eye_shape = "圆眼短睫"
      else
        eye_shape = "无"

      var temp = { }
      //数据库存储
      wx.getStorage({
        key: 'login_info',
        success (res) {
          temp = {
            id_user : res.data._id,
            id_test : that.data.load_time,
            navid : navid,
            year : year,
            month : month,
            day : day,
            time : `${hours}:${minutes}`,
            eye_shape : eye_shape,         
            image_main : temp_image_main,
            image_main_shut : temp_image_main_shut,
          }
          const db = wx.cloud.database()
          const todo = db.collection('record-test')
          todo.add({ data: temp, })
        }
      })
      wx.setStorage({ key : "last_analysis", data :  temp}) //缓存上次检测信息
    },2000)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    const sysinfo = wx.getSystemInfoSync()
    that.setData({
      layout_height: sysinfo.screenHeight,
      camera_face_audio : wx.createInnerAudioContext({ useWebAudioImplement: true }),    //获取音频上下文对象
      load_time: Date.now()
    })

    //that.audiio_start("0700")
    setTimeout(() => {
      that.audiio_start("0101")
      that.get_image();
    }, 2000);
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.offAccelerometerChange();
  },
  //监听页面数据更新
  onShow(){
    let that = this
    that.setData({
      load_time: Date.now(),

      flag_main : false,
      flag_main_shut : false,
      image_main : "",
      image_main_shut : "",

      current_image : "face_main",
    })

    setTimeout(() => {
      that.audiio_start("0101")
      that.get_image();
    }, 2000);
  }

})